<?php

class RoleController extends ControllerBase
{

    public function indexAction()
    {
        $this->view->roles       = OaRoles::getAll();
        $this->view->departments = OaDepartments::getAll();
    }

    public function modalAction($user_id = 0)
    {
        $role = array();
        if ($user_id) {
            $role = OaRoles::getOne($user_id);
            foreach ($this->langs as $lang => $t) {
                $role['description.' . $lang] = db_translate($role['description'], 'role', $user_id, $lang);
            }
        }

        $this->view->role = $role;
        $this->view->departments = OaDepartments::getAll();
    }

    public function saveAction()
    {
        $request = $this->request;

        if ($request->isPost()) {
            $user_id = $request->getPost('role_id', 'int');
            $descriptions = $request->getPost('description');

            if ($user_id) {
                $model = OaRoles::findFirst('role_id=' . $user_id);
            } else {
                $model = new OaRoles;
            }

            $data = array(
                'dept_id'  => $request->getPost('dept_id', 'int'),
                'description' => $descriptions['en-us'],
                'sort_order' => $request->getPost('sort_order', 'int'),
            );

            if ($model->save($data)) {
                // 写入其它语言部门名称
                foreach ($descriptions as $lang => $text) {
                    OaTranslates::write('role', $model->role_id, $text, $lang);
                }

                return $this->ajax->success();
            }

            return $this->ajax->error($model->getMessage());
        }
    }

    public function deleteAction($user_id)
    {
        if (! $model = OaRoles::findFirst('role_id=' . $user_id)) {
            return $this->ajax->error(__('The record not found'));
        }

        if ($model->protected) {
            return $this->ajax->error(__('This role is protected can not be deleted'));
        }

        if ($model->delete()) {
            return $this->ajax->success();
        }

        return $this->ajax->error($model->getMessage());
    }

}
